"use strict"

let mongoose 	= require('mongoose');
let Schema 		= mongoose.Schema;

let _ 						= require("lodash")
	, bcrypt	 			= require('bcrypt-as-promised') //A promise version of bcrypt
	, randomstring 	= require("randomstring")
	, debug					= require('debug')('models')
	, Promise 			= require('bluebird');

//-- Delcare Variables --//
var SALT_WORK_FACTOR 	= 10;

let ClientSchema = new Schema({
	name: String,
	secret: { type: String, require: true },
  account: { type: Schema.Types.ObjectId, ref: 'Account', required: true },
	createdAt : { type: Date, default: Date.now },
	updatedAt : { type: Date },
	deletedAt : { type: Date }
});


ClientSchema.statics.generateClient = function(account, cb){
		var clientSecretClearText = randomstring.generate();
		// generate a salt
		bcrypt.genSalt(SALT_WORK_FACTOR)
			.then(function(salt) {
				debug("salt: ", salt);
				// hash the password using our new salt
				//We don't need to persist the SALT because it has already been incorprated into the hash
				// http://stackoverflow.com/questions/277044/do-i-need-to-store-the-salt-with-bcrypt

				return bcrypt.hash(clientSecretClearText, salt);
			})
			.then(function(hash) {
				debug("hash: ", hash);
				// override the cleartext password with the hashed one
				var client = new Client({
								_id: mongoose.Types.ObjectId("56f6bff4caa511fd56c94d88"),
								secret: hash,
                account: account
							});

        client.save(function(err, client){
            if( err ) return cb(err);

            debug("client create success");
            return cb(null, client);
        });
			})
			.catch(function(err){
				debug("Create Client Error: ", err);
				return cb(err);
			});
};

ClientSchema.statics.generateClientAsync = Promise.promisify(ClientSchema.statics.generateClient);

ClientSchema.methods.compareClientSecrect = function(candidateSecret, cb){
	var client = this;;

	bcrypt.compare(candidateSecret, client.secret, function(err, isMatch) {
			if (err) return cb(err);
			cb(null, isMatch);
	});
}

var Client = mongoose.model('Client', ClientSchema);
module.exports = Client;
